<template>
  <BasicForm @register="registerForm" />
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema04 } from '../Goods.data';
  import { saveOrUpdate } from '../Goods.api';
  import { Colors } from '/@/utils/dict/DictColors.js';

  // Emits声明
  const emit = defineEmits(['register', 'handleOk', 'error']);
  const isUpdate = ref(true);
  const props = defineProps({
    isUpdate: {
      type: Boolean,
      default: false,
    },
    record: {
      type: Object,
      default: () => ({}),
    },
  });

  // 内部 isUpdate 状态
  const internalIsUpdate = ref(false);
  //表单配置
  const [registerForm, { setFieldsValue, validate }] = useForm({
    labelWidth: 200,
    schemas: formSchema04,
    showActionButtonGroup: false,
  });

  //表单提交事件
  async function handleSubmit(v) {
    console.log('第三个页切的表单数据', v);
    try {
      let values = await validate();
      //提交表单
      console.log('第三个页切的表单数据', values);
      // 添加产品主ID到提交数据中
      // if (props.record && props.record.id) {
      values.id = props.record.id;
      // }
      values.goodsEnglish = JSON.stringify(values);
      const result = await saveOrUpdate(values, unref(internalIsUpdate) || props.isUpdate);
      // 提交成功后触发事件
      return { success: true, data: result };
    } catch (error) {
      emit('error', error);
      return { success: false, error };
    }
  }
  // 设置表单值
  function setFormValues(values: any) {
    // if (values.goodsEnglish) {
    setFieldsValue({
      id: values.id,
      goodsCode: values.goodsCode,
      ...JSON.parse(values.goodsEnglish),
    });
    // }
  }
  // 设置更新模式
  function setIsUpdate(value: boolean) {
    internalIsUpdate.value = value;
  }

  defineExpose({
    handleSubmit,
    setFormValues,
    setIsUpdate,
  });
</script>

<style lang="less" scoped>
  /*begin 字典颜色配置样式*/
  .item-tool {
    display: flex;
    flex-wrap: wrap;
    .item-color {
      width: 18px;
      display: flex;
      justify-content: center;
      cursor: pointer;
      align-items: center;
      margin-right: 10px;
    }
    .item-back {
      width: 18px;
      height: 18px;
      border-radius: 50%;
    }
  }
  .item-color-border {
    visibility: hidden;
  }
  .item-active .item-color-border {
    visibility: visible;
    position: absolute;
    border: 1px solid;
    width: 24px;
    height: 24px;
    border-radius: 50%;
  }
  /*end 字典颜色配置样式*/
</style>
